package com.example.mysimpleexample.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.example.mysimpleexample.R;
import com.flipboard.bottomsheet.BottomSheetLayout;
import com.flipboard.bottomsheet.commons.ImagePickerSheetView;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class ImagePickerActivity extends AppCompatActivity {
    public static final int REQUEST_STORAGE = 0;
    public static final int REQUEST_IMAGE_CAPTURE = REQUEST_STORAGE + 1;
    public static final int REQUEST_LOAD_IMAGE = REQUEST_IMAGE_CAPTURE + 1;
    private BottomSheetLayout bottomSheet;
    private Uri cameraImageUri = null;
    private ImageView selectedImage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_picker);
        bottomSheet = findViewById(R.id.bottom_sheet);
        bottomSheet.setPeekOnDismiss(true);
        selectedImage = findViewById(R.id.image_picker_selected);
        findViewById(R.id.image_picker_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkNeedsPermission()) {
                    requestStoragePermission();
                }else{
                    showSheetView();
                }
            }
        });
    }

    private boolean checkNeedsPermission(){
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && ActivityCompat.checkSelfPermission(ImagePickerActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void requestStoragePermission(){
        ActivityCompat.requestPermissions(ImagePickerActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_STORAGE );
    }

    private void showSheetView(){
        ImagePickerSheetView sheetView = new ImagePickerSheetView.Builder(this)
                .setMaxItems(30)
                .setShowCameraOption(true)
                .setShowPickerOption(true)
                .setImageProvider(new ImagePickerSheetView.ImageProvider() {
                    @Override
                    public void onProvideImage(ImageView imageView, Uri imageUri, int size) {
                        Glide.with(ImagePickerActivity.this)
                                .load(imageUri)
                                .centerCrop()
                                .into(imageView);
                    }
                })
                .setOnTileSelectedListener(new ImagePickerSheetView.OnTileSelectedListener() {
                    @Override
                    public void onTileSelected(ImagePickerSheetView.ImagePickerTile selectedTile) {
                        bottomSheet.dismissSheet();
                        if (selectedTile.isCameraTile()) {
                            dispatchTakePickerIntent();
                        }else if(selectedTile.isPickerTile()){
                            startActivityForResult(createPickIntent(),REQUEST_LOAD_IMAGE);
                        }else if(selectedTile.isImageTile()){
                            showSelectedImage(selectedTile.getImageUri());
                        }else{

                        }
                    }
                })
                .setTitle("选择文件...")
                .create();
        bottomSheet.showWithSheetView(sheetView);
    }

    @NonNull
    private Intent createPickIntent(){
        Intent picImageIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        if (picImageIntent.resolveActivity(getPackageManager()) != null) {
            return picImageIntent;
        }else{
            return null;
        }
    }

    @NonNull
    private Intent createCameraIntent(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getPackageManager()) != null) {
            return intent;
        }else{
            return null;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            Uri selectedImageUri = null;
            if (requestCode == REQUEST_LOAD_IMAGE && data != null) {
                selectedImageUri = data.getData();
                if (selectedImageUri == null) {
                    generateError();
                }
            }else if(requestCode == REQUEST_IMAGE_CAPTURE){
                selectedImageUri = cameraImageUri;
            }
            if (selectedImageUri != null) {
                showSelectedImage(selectedImageUri);
            }else{
                generateError();
            }
        }
    }

    private void generateError() {

    }

    private void showSelectedImage(Uri selectedImageUri){
        selectedImage.setImageDrawable(null);
        Glide.with(this)
                .load(selectedImageUri)
                .fitCenter()
                .into(selectedImage);
    }

    private void dispatchTakePickerIntent(){
        Intent takePickerIntent = createCameraIntent();
        if (takePickerIntent != null) {
            try {
                File imageFile = createImageFile();
                takePickerIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(imageFile));
                startActivityForResult(takePickerIntent,REQUEST_IMAGE_CAPTURE);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File imageFile = File.createTempFile(imageFileName,".JPG",storageDir);
        cameraImageUri = Uri.fromFile(imageFile);
        return imageFile;
    }
}